package webbandidong.controller.accountcontroller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import webbandidong.bo.AdminBO;
import webbandidong.model.Admin;
import webbandidong.util.Constant;
import webbandidong.viewmodel.AdminLoginViewModel;

public class AdminLoginController extends SimpleFormController {

    @Autowired
    private AdminBO adminBO;

    public void setAdminBOImpl(AdminBO adminBO) {
        this.adminBO = adminBO;
    }

    public AdminLoginController() {

        setCommandClass(AdminLoginViewModel.class);
        setCommandName("adminLoginViewModel");
        setSuccessView("admin/manage/showmobiles");
        setFormView("admin/account/adminlogin");
    }

    @Override
    protected ModelAndView onSubmit(
            HttpServletRequest request, 
            HttpServletResponse response, 
            Object command, 
            BindException errors) throws Exception {

        AdminLoginViewModel model = (AdminLoginViewModel)command;
        int adminId = Integer.parseInt(adminBO.checkExists(new Admin(0, model.getUsername(), model.getPassword())));

        HttpSession session = request.getSession();
        session.setAttribute(Constant.USER_ID, adminId);
        session.setAttribute(Constant.USER_NAME, model.getUsername());
        session.setAttribute(Constant.USER_ROLE, Constant.ADMIN_ROLE);

        String returnUrl = request.getParameter("returnurl");
        if (returnUrl != null && !"".equals(returnUrl)) {
            response.sendRedirect(returnUrl);
            return null;
        }
        else {
//            return new ModelAndView(getSuccessView());
            response.sendRedirect("/admin/manage/showmobiles.htm");
            return null;
        }
    }
}